/*
 * Exploder
 * 
 * Tero Pyylampi (218437), Jussi Tuurinkoski (211594)
 *
 * Ground object for the game, contains one static long ground item
 * and sprites related to it
 */

#include "GameGround.h"
#include "../../../../Common.h"
#include "../../../../Resources.h"

using namespace cocos2d;

// default constructor
GameGround::GameGround( b2World *world, cocos2d::CCLayer *layer, float groundWidth )
	: GamePhysicObject( world ), mLayer( layer ) {
	// init physics ground
	b2BodyDef groundDef;
	groundDef.type = b2_staticBody;
	groundDef.position.Set( 0, WORLD_HEIGHT * 0.05f - 1.0f );
	b2Body *groundBody = mGameWorld->CreateBody( &groundDef );
	groundBody->SetUserData( this );

	// set shape for body
	b2PolygonShape groundShape;
	groundShape.SetAsBox( groundWidth * 2.0f, 1.0f );

	// create fixture for body
	b2FixtureDef groundFix;
	groundFix.shape = &groundShape;
	groundFix.density = 1.0f;
	groundFix.friction = 0.3f;
	groundFix.restitution = 0.2f;

	// attach fixture into a body
	groundBody->CreateFixture( &groundFix );
	mBodies->push_back( groundBody );

	// init ground sprites
	unsigned int amountOfGroundSprites = std::ceil( groundWidth / 10.f );
	for( unsigned int i = 0; i <= amountOfGroundSprites; ++i ) {
		GroundSpriteCombo newCombo;
		newCombo.lowerGroundSprite = CCSprite::spriteWithFile( getResource( Textures::GAME_GROUND_GRASS ) );
		newCombo.upperGroundSprite = CCSprite::spriteWithFile( getResource( Textures::GAME_GROUND_DIRT ) );
		
		// set scales and positions
		newCombo.lowerGroundSprite->setScaleX( RATEX );
		newCombo.lowerGroundSprite->setScaleY( RATEY );
		newCombo.upperGroundSprite->setScaleX( RATEX );
		newCombo.upperGroundSprite->setScaleY( RATEY );
		newCombo.lowerGroundSprite->setPosition( ccp( WIN_WIDTH / 2.0f - amountOfGroundSprites / 2.0f * ( WIN_WIDTH / 4.0f ) + i * ( WIN_WIDTH / 4.0f ), WIN_HEIGHT * 0.05f ) );
		newCombo.upperGroundSprite->setPosition( ccp( WIN_WIDTH / 2.0f - amountOfGroundSprites / 2.0f * ( WIN_WIDTH / 4.0f ) + i * ( WIN_WIDTH / 4.0f ), -WIN_HEIGHT * 0.2f ) );

		// add sprites as childs
		mLayer->addChild( newCombo.lowerGroundSprite, Z_LAYER_FOREGROUND );
		mLayer->addChild( newCombo.upperGroundSprite, Z_LAYER_FOREGROUND );
		mGroundSprites.push_back( newCombo );
	}
}

// default destructor
GameGround::~GameGround() {
	// remove sprites
	for( unsigned int i = 0; i < mGroundSprites.size(); ++i ) {
		mLayer->removeChild( mGroundSprites.at( i ).upperGroundSprite, true );
		mLayer->removeChild( mGroundSprites.at( i ).lowerGroundSprite, true );
	}
}

// default update function
void GameGround::update( cocos2d::ccTime dt ) {
	GamePhysicObject::update( dt );
}

// get the main type of the object
PhysicObjectItems GameGround::getObjectType() {
	return ELEMENT_GROUND;
}